package net.huashitong.supervision.task.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.util.PasswordHelper;
import com.sirdc.modules.sys.util.SysGlobals;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.entity.TimeLimit;
import net.huashitong.supervision.task.util.ExcelReaderUtil;
import net.huashitong.supervision.task.util.HolidayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/9/10
 * Time: 20:29
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class UserManageService extends StringPKService<SysUser> {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private PasswordHelper passwordHelper;

    @Override
    protected BaseDao<SysUser, String> getDao() {
        return sysUserDao;
    }

    /**
     * 返回当前单位用户信息
     *
     * @param filter
     * @return
     */
    public List<SysUser> queryFilter(SysUserFilter filter) {
        String deptId = SysUserUtils.getDeptId();
        filter.setDeptId(deptId);
        List<SysUser> userList = sysUserDao.queryFilter(filter);
        return userList;
    }
    public void save(SysUser obj, String userId){
        Date date = new Date();
        String date1 = HolidayUtils.sdf1.format(date);
        String time = HolidayUtils.sdf2.format(date);
        obj.setSysId(tableService.updateMaxSysId("t_sys_user",null));
        obj.setCreateUser(userId);
        obj.setUpdUser(userId);
        obj.setCreateDate(date1);
        obj.setCreateTime(time);
        obj.setUpdDate(date1);
        obj.setUpdTime(time);
        getDao().save(obj);
    }
    public void addUser(SysUserDataBean databean) {
        databean.setUserId(tableService.updateMaxSysId("t_sys_user", null));
        String deptId = SysUserUtils.getDeptId();
        SysDept dept = deptService.getById(deptId);
        String username = databean.getUsername();
        //去空格
        username=  username.replace(" ", "");
        //检测用户是否已经存在
        if (sysLoginService.isExistForUsername(username)) {
            if (dept.getDeptName().equals(username)){
                throw new SystemException(username+"为公共账号，无法添加相同用户名，请重新添加用户");
            }
            //查询当前单位用户是存在该用户
            if (sysLoginService.isExistForUsernameDept(username, deptId)) {
                List<SysLogin> sysLogins = sysLoginService.getByUsernameDept(username, deptId);
                if (ObjectUtils.isNotBlank(sysLogins)) {
                    for (SysLogin sysLogin : sysLogins) {
                        SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                        if (StringUtils.isNotBlank(databean.getMobile())) {
                            sysUser.setMobile(databean.getMobile());
                        }
                        if (StringUtils.isNotBlank(databean.getPassword())) {
                            sysLogin.setPassword(databean.getPassword());
                            passwordHelper.encryptPassword(sysLogin);
                        }
                        if (StringUtils.isNotBlank(databean.getPosition())) {
                            sysUser.setPosition(databean.getPosition());
                        }
                        if (StringUtils.isNotBlank(databean.getRoleId())) {
                            sysLogin.setRoleId(databean.getRoleId());
                        }
                        sysUser.setState("01");
                        sysLogin.setState("启用");
                        sysLoginService.update(sysLogin);
                        sysUserDao.update(sysUser);
                    }
                } else {
//                            return "用户名已存在其他单位: "+lists.get(i).get(0);
                    throw new UserExistException(username);
                }
                return;
            }
        }

        //保存用户信息
        SysUser user = new SysUser();
        user.setUserId(databean.getUserId());
        user.setSysId(databean.getUserId());
        user.setBirthday(databean.getBirthday());
        user.setDemo(databean.getDemo());
        user.setPosition(databean.getPosition());
        user.setName(databean.getName());
        user.setGender(databean.getGender());
        user.setNativeAddr(databean.getNativeAddr());
        user.setState(SysGlobals.AccountStates.NOMAL);//状态为正常
        user.setIdCard(databean.getIdCard());
        user.setAddress(databean.getEmail());
        user.setMobile(databean.getMobile());
        sysUserDao.save(user);

        //保存登陆信息
        SysLogin login = new SysLogin();
        login.setUsername(username);
        if (StringUtils.isNotBlank(databean.getDeptId())) {
            login.setDeptId(databean.getDeptId());
        } else {
            throw new NullPointerException(databean.getDeptId());
        }
        login.setPassword(databean.getPassword());
        login.setRoleId(databean.getRoleId());
        login.setSysId(user.getUserId());
        sysLoginService.save(login);
    }

    /**
     * 单位导入用户信息表格
     *
     * @param inputStream
     * @param name
     * @return
     */
    public String createUserExcel(InputStream inputStream, String name) {
        if (StringUtils.isNotBlank(SysUserUtils.getUserId())) {
            String deptId = SysUserUtils.getDeptId();
            SysDept dept = deptService.getById(deptId);
            List<List<String>> lists = ExcelReaderUtil.readExcel(inputStream, name);
            List<SysUserDataBean> userDataBeans = new ArrayList<>();
            if (ObjectUtils.isNotBlank(lists)) {
                for (int i = 1; i < lists.size(); i++) {
                    String role = lists.get(i).get(2);//角色
                    //检测用户是否已经存在
                    String username = lists.get(i).get(0);
                    //去空格
                    username=username.replace(" ", "");
                    if (sysLoginService.isExistForUsername(username)) {
                        if (dept.getDeptName().equals(username)){
                            throw new SystemException(username+"为公共账号，无法添加相同用户名，请重新添加用户");
                        }
                        //查询当前单位用户是存在该用户
                        if (sysLoginService.isExistForUsernameDept(username, deptId)) {
                            List<SysLogin> sysLogins = sysLoginService.getByUsernameDept(username, deptId);
                            if (ObjectUtils.isNotBlank(sysLogins)) {
                                for (SysLogin sysLogin : sysLogins) {
                                    SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                                    if (StringUtils.isNotBlank(lists.get(i).get(1))) {
                                        sysUser.setMobile(lists.get(i).get(1));
                                    }
                                    sysLogin.setPassword("123456");
                                    if (StringUtils.isNotBlank(lists.get(i).get(3))) {
                                        sysUser.setPosition(lists.get(i).get(3));
                                    }
                                    if (StringUtils.isNotBlank(lists.get(i).get(2))) {
                                        //判断用户角色
                                        String roleId = "县领导".equals(role) ? "01" : "主要领导".equals(role) ? "02" : "分管领导".equals(role) ? "03" : "经办人".equals(role) ? "04" : "00";
                                        sysLogin.setRoleId(roleId);
                                    }
                                    if (StringUtils.isNotBlank(sysLogin.getPassword())) {
                                        passwordHelper.encryptPassword(sysLogin);
                                    }
                                    sysUser.setState("01");
                                    sysLogin.setState("启用");
                                    sysLoginService.update(sysLogin);
                                    sysUserDao.update(sysUser);
                                }
                            } else {
//                            return "用户名已存在其他单位: "+username;
                                throw new UserExistException(username);
                            }
                            continue;
                        }
                    }
                    //保存用户信息
                    SysUser sysUser = new SysUser();
                    String userId = tableService.updateMaxSysId("t_sys_user", null);
                    sysUser.setSysId(userId);
                    sysUser.setUserId(userId);
                    if (StringUtils.isNotBlank(username)) {
                        sysUser.setName(username);//姓名
                    } else {
                        return "第" + i + "行请填写用户名";
                    }
                    sysUser.setMobile(lists.get(i).get(1));//电话
                    sysUser.setPosition(lists.get(i).get(3));//职务
                    sysUser.setState("01");//正常
                    sysUserDao.save(sysUser);

                    //保存登录信息
                    SysLogin sysLogin = new SysLogin();
                    //判断用户角色
                    String roleId = "县领导".equals(role) ? "01" : "主要领导".equals(role) ? "02" : "分管领导".equals(role) ? "03" : "经办人".equals(role) ? "04" : "00";
                    if (StringUtils.isNotBlank(deptId)) {
                        sysLogin.setDeptId(deptId);
                    } else {
                        return "登录超时，请刷新页面重新登录";
                    }
                    sysLogin.setUsername(username);
                    sysLogin.setPassword("123456");
                    sysLogin.setRoleId(roleId);
                    sysLogin.setSysId(userId);
                    sysLoginService.save(sysLogin);
                }
            }
            return "200";
        } else {
            return "登录超时，请刷新页面重新登录";
        }
    }


    /**
     * 导单位公用账号用户信息表格
     *
     * @param inputStream
     * @param name
     * @return
     */
    public String createDeptUserExcel(InputStream inputStream, String name) throws Exception {
        String deptId = SysUserUtils.getDeptId();
        List<List<String>> lists = ExcelReaderUtil.readExcel(inputStream, name);
        List<SysUserDataBean> userDataBeans = new ArrayList<>();
        if (ObjectUtils.isNotBlank(lists)) {
            for (int i = 1; i < lists.size(); i++) {
                //检测用户是否已经存在
                if (sysLoginService.isExistForUsername(lists.get(i).get(0))) {
                    //查询当前单位用户是存在该用户
                    if (sysLoginService.isExistForUsernameDept(lists.get(i).get(0), deptId)) {
                        List<SysLogin> sysLogins = sysLoginService.getByUsernameDept(lists.get(i).get(0), deptId);
                        if (ObjectUtils.isNotBlank(sysLogins)) {
                            for (SysLogin sysLogin : sysLogins) {
                                SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                                sysUser.setState("01");
                                sysLogin.setState("启用");
                                sysLoginService.update(sysLogin);
                                sysUserDao.update(sysUser);
                            }
                        } else {
//                            return "用户名已存在其他单位: "+lists.get(i).get(0);
                            throw new UserExistException(lists.get(i).get(0));
                        }
                    }
                }
                //保存用户信息
                SysUser sysUser = new SysUser();
                String userId = tableService.updateMaxSysId("t_sys_user", null);
                sysUser.setSysId(userId);
                sysUser.setUserId(userId);
                sysUser.setName(lists.get(i).get(0));//姓名
                sysUser.setMobile(lists.get(i).get(1));//电话
                sysUser.setPosition("公共账号");//职务
                sysUser.setState("01");//正常
                sysUserDao.save(sysUser);

                //保存登录信息
                SysLogin sysLogin = new SysLogin();
                String role = lists.get(i).get(2);//角色
                //判断用户角色
                String roleId = "主要领导".equals(role) ? "02" : "分管领导".equals(role) ? "03" : "经办人".equals(role) ? "04" : "00";
                List<SysDept> depts = deptService.getByName(lists.get(i).get(0));
                if (depts.size() > 1) {
                    throw new Exception("单位名称重复");
                } else if (depts.size() == 0) {
                    throw new Exception("单位不存在");
                }
                sysLogin.setDeptId(depts.get(0).getSysId());
                sysLogin.setUsername(lists.get(i).get(0));
                sysLogin.setPassword("123456");
                sysLogin.setRoleId("02");
                sysLogin.setSysId(userId);
                sysLoginService.save(sysLogin);
            }
        }
        return "200";
    }

    public List<SysUser> getByDeptId(SysUserFilter filter) {
        return sysUserDao.queryFilter(filter);
    }
}
